package com.demo.common.web.exception;

import com.demo.common.core.entity.Result;
import com.demo.common.core.exception.AppException;
import com.demo.common.core.exception.SystemErrorType;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
 * 全局异常，所有服务通用异常捕获在这里写
 * Created by zh-ma
 * Date 2019/9/16 ${Time}
 */
public class DefaultGlobalExceptionHandlerAdvice {



    //json格式
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result errorHandler(MethodArgumentNotValidException ex) {
        StringBuilder errorMsg = new StringBuilder();
        BindingResult re = ex.getBindingResult();
        for (ObjectError error : re.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(",");
        }
        errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
        return  Result.fail(SystemErrorType.PARAM_ERROR,errorMsg.toString(),null);

    }


    //表单格式
    @ExceptionHandler(value = BindException.class)
    public Result errorHandler(BindException ex) {
        BindingResult result = ex.getBindingResult();
        StringBuilder errorMsg = new StringBuilder();
        for (ObjectError error : result.getAllErrors()) {
            errorMsg.append(error.getDefaultMessage()).append(",");
        }
        errorMsg.delete(errorMsg.length() - 1, errorMsg.length());
        return  Result.fail(SystemErrorType.PARAM_ERROR,errorMsg.toString(),null);
    }



    @ExceptionHandler(AppException.class)
    //返回错误码401
//    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public Result appThrowableException(AppException ex){
        return Result.fail(ex);
    }



    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public Result exception(Exception ex) throws Exception {
        if (AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class) != null) {
            throw ex;
        }
        return Result.fail(SystemErrorType.SERVICE_ERROR,ex.getMessage(),null);
    }

    @ExceptionHandler(value = {Throwable.class})
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result throwable() {
        return Result.fail();
    }
}